package com.itheima.server.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.server.Enum.ClueStatus;
import com.itheima.server.domain.CluBusSave;
import com.itheima.server.domain.Clue;
import com.itheima.server.service.ClueService;
import com.itheima.server.service.RuleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class ClueJob {

    @Autowired
    private RuleService ruleService;
    @Autowired
    private ClueService clueService;


    public void executeClue() {
        log.info("线索定时任务开始");
        //逻辑：最后更新时间+限制时间>=当前时间触发回收
        //获取定时任务参数
        LambdaQueryWrapper<CluBusSave> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CluBusSave::getType, 0);
        CluBusSave busSave = ruleService.getOne(wrapper);
        Integer limitTime = busSave.getLimitTime();
        String limitTimeType = busSave.getLimitTimeType();

        //获取遍历商机详情
        List<Clue> list = clueService.list();

        for (Clue clue : list) {


            //判断线索最后更新时间是否为空
            if (clue.getUpdateTime() == null) {
                continue;
            }

            //判断是否在线索池
            if (clue.getStatus().equals(ClueStatus.INVALID.status)) {
                continue;
            }

            //小时
            if (limitTimeType.equals("0")) {
                if (clue.getUpdateTime().getTime() + limitTime * 60 * 60 * 1000 <= System.currentTimeMillis()) {
                    updateStatus(clue);
                    continue;
                }
            }

            //天
            if (limitTimeType.equals("1")) {
                if (clue.getUpdateTime().getTime() + limitTime* 24 * 60 * 60 * 1000 <= System.currentTimeMillis()) {
                    updateStatus(clue);
                    continue;
                }
            }

            //周
            if (limitTimeType.equals("2")) {
                if (clue.getUpdateTime().getTime() + limitTime *7 * 24 * 60 * 60 * 1000 <= System.currentTimeMillis()) {
                    updateStatus(clue);
                    continue;
                }
            }

        }
        log.info("商机定时任务结束");




    }

    //修改状态方法

    private void updateStatus(Clue clue) {
        //将线索放入线索池
        clue.setOwner(null);
        clue.setStatus(ClueStatus.INVALID.status.toString());
        clue.setUpdateTime(new Date());
        clueService.updateById(clue);
    }


}


